//
//  Player.m
//  LoveToListen
//
//  Created by apple on 16/4/10.
//  Copyright © 2016年 LanOu. All rights reserved.
//

#import "Player.h"
#import "RadioSongModel.h"
#import "SongModel.h"
#import <MediaPlayer/MPMediaItem.h>
#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMusicPlayerController.h>
#import <MediaPlayer/MPVolumeView.h>
#import "UIImageView+WebCache.h"

@interface Player ()

@end

@implementation Player

+ (instancetype)shareInstance{
    static Player *player = nil;
    static dispatch_once_t once = 0;
    dispatch_once(&once, ^{
        player  = [[Player alloc] init];
    });
    return player;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [NOTIFICATION_CENTER addObserver:self selector:@selector(addSongs:) name:@"playSongs" object:nil];
        [NOTIFICATION_CENTER addObserver:self selector:@selector(stopPlay:) name:@"stopPlay" object:nil];
    }
    return self;
}

- (STKAudioPlayer *)player{
    if (!_player) {
        STKAudioPlayerOptions playerOptions = {YES, YES, {50, 100, 200, 400, 800, 1600, 2600, 16000}};
        self.player = [[STKAudioPlayer alloc] initWithOptions:playerOptions];
        self.player.delegate = self;
       
    }
    return self.player;
}

- (void)addSongs:(NSNotification *)notification{
    if ([notification.userInfo[@"type"] isEqualToString:@"RadioSong"]) {
        self.type = 1;
        if (self.songArr != notification.object) {
            self.songArr = notification.object;
            self.num = 0;
            [self stop];
        }
    }
    if ([notification.userInfo[@"type"] isEqualToString:@"Song"]) {
        self.type = 2;
        if (self.songArr != notification.object) {
            self.songArr = notification.object;
            NSIndexPath *tempIndexPath = notification.userInfo[@"indexPath"];
            self.num = tempIndexPath.row;
            [self stop];
        } else if (self.num != [notification.userInfo[@"indexPath"] row]){
            self.num = [notification.userInfo[@"indexPath"] row];
            [self stop];
        }
    }
    if ([notification.userInfo[@"type"] isEqualToString:@"Download"]) {
        self.type = 3;
        
        if (self.songArr != notification.object) {
            self.songArr = notification.object;
            NSIndexPath *tempIndexPath = notification.userInfo[@"indexPath"];
            self.num = tempIndexPath.row;
            
            [self.player stop];
            
        } else if (self.num != [notification.userInfo[@"indexPath"] row]){
            self.num = [notification.userInfo[@"indexPath"] row];
            //            [self.player stop];
        }
    }
    [self play];
}

- (void)stopPlay:(NSNotification *)notification{
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self pause];
    }
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self resume];
    }
}

- (void)play{
    if (self.songArr.count) {
        if (STKAudioPlayerStatePlaying == self.player.state) {
            [self.player pause];
            
            if (self.type == 1) {
                [NOTIFICATION_CENTER postNotificationName:@"radioStop" object:nil];
            }
            
        } else if (STKAudioPlayerStatePaused == self.player.state) {
            
            // 继续
            [self.player resume];
            
            if (self.type == 1) {
                [NOTIFICATION_CENTER postNotificationName:@"radioStop" object:nil];
            }
            
        } else {
            self.title = nil;
            self.singer = nil;
            self.imgUrl = nil;
            self.imgName = nil;
            
            if (self.type == 1) {
                RadioSongModel *radioSongModel = _songArr[self.num];
                [self playUrl:radioSongModel.url_list[0][@"url"]];
                self.title = radioSongModel.song_name;
                self.singer = radioSongModel.singer_name;
                self.imgName = @"default_nsonglist";
            }
            if (self.type == 2) {
                SongModel *songModel = _songArr[self.num];
                if (songModel.urlList.count != 0) {
                    [self playUrl:songModel.urlList[0][@"url"]];
                }
                self.title = songModel.name;
                self.singer = songModel.singerName;
                self.imgUrl = songModel.picUrl;
            }
            if (self.type == 3) {
                NSDictionary *dic = self.songArr[self.num];
                NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *path = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"db/%@",dic[@"path"]]];
                [self playFile:path];
                
                self.title = dic[@"name"];
                self.singer = dic[@"singerName"];
                if ([dic[@"picUrl"] length]) {
                    self.imgUrl = dic[@"picUrl"];
                }else{
                    self.imgName = @"default_nsonglist";
                }
            }
            
            [NOTIFICATION_CENTER postNotificationName:@"playerInfo" object:self.songArr userInfo:@{@"type":@(self.type),@"num":@(self.num)}];
        }
    }
}

- (void) playUrl:(NSString *)str{
    //    [self stop];
    //    self.player = nil;
    [self.player play:str];
}

- (void) playFile:(NSString *)path{
    //    [self stop];
    //    self.player = nil;
    NSURL *url = [NSURL fileURLWithPath:path];
    [self.player playURL:url];
}

- (void)stop{
    //    [self.player stop];
    //    if (self.player.state == STKAudioPlayerStatePaused) {
    self.player.state = STKAudioPlayerStateStopped;
    //    }
}

- (void)pause{
    [self.player pause];
}

- (void)resume{
    [self.player resume];
}

- (void)nextSong{
    if (self.num <= (self.songArr.count - 1)) {
        if (self.circleType == 0) {
            if (self.num == self.songArr.count - 1) {
                self.num = 0;
            } else{
                self.num++;
            }
        } else if (self.circleType == 1){
            
        } else {
            self.num = arc4random() % (self.songArr.count);
        }
        
        [self stop];
        
        [self play];
        
    }
}

- (void)frontSong{
    if (self.num <= (self.songArr.count - 1)) {
        if (self.circleType == 0) {
            if (self.num == 0) {
                self.num = self.songArr.count - 1;
            } else {
                self.num--;
            }
        } else if (self.circleType == 1){
            
        } else {
            self.num = arc4random() % (self.songArr.count);
        }
        
        [self stop];
        
        [self play];
    }
}

- (void)configNowPlayingInfoCenter{
    if (self.songArr.count && (self.player.state = STKAudioPlayerStatePlaying)) {
        if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:self.title forKey:MPMediaItemPropertyTitle];//歌名
            [dict setObject:self.singer forKey:MPMediaItemPropertyArtist];//歌手
            //            [dict setObject:@"清风至上" forKey:MPMediaItemPropertyAlbumTitle];//专辑
            UIImage *image = nil;
            if (!self.imgName) {
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imgUrl]];
                image = [UIImage imageWithData:data];//歌手图片
            } else {
                image = [UIImage imageNamed:self.imgName];
            }
            
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
            
            [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
            
            [dict setObject:[NSNumber numberWithFloat:self.player.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
            
            [dict setObject:[NSNumber numberWithFloat:0.1] forKey:MPNowPlayingInfoPropertyDefaultPlaybackRate];
            
            [dict setObject:[NSNumber numberWithFloat:self.player.duration] forKey:MPMediaItemPropertyPlaybackDuration];
            
            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
            
        }
    }
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    if (audioPlayer == self.player) {
        
        if ((self.num <= (self.songArr.count - 1)) && (stopReason == 1)) {
            if (self.circleType == 0) {
                if (self.num == self.songArr.count - 1) {
                    self.num = 0;
                } else{
                    self.num++;
                }
            } else if (self.circleType == 1){
                
            } else {
                self.num = arc4random() % (self.songArr.count);
            }
            
            [self play];
        }
    }
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId{
    [self configNowPlayingInfoCenter];
    [self performSelector:@selector(configNowPlayingInfoCenter) withObject:nil afterDelay:1];
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId{
    [self configNowPlayingInfoCenter];
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    [self configNowPlayingInfoCenter];    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    
}




@end
